package com.qsl.system.fillter;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qsl.common.result.Result;
import com.qsl.common.result.ResultCodeEnum;
import com.qsl.common.util.IpUtil;
import com.qsl.common.util.JwtHelper;
import com.qsl.common.util.ResponseUtil;
import com.qsl.model.vo.LoginVo;
import com.qsl.system.custom.CustomUser;
import com.qsl.system.service.LoginLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义用户认证接口
 * 登录过滤器，继承UsernamePasswordAuthenticationFilter，对用户名密码进行登录校验
 */
public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {

    //    Redis
    private RedisTemplate redisTemplate;

    private LoginLogService loginLogService;


    public TokenLoginFilter(AuthenticationManager authenticationManager, RedisTemplate redisTemplate, LoginLogService loginLogService) {
        this.setAuthenticationManager(authenticationManager);
        this.setPostOnly(false);
        // 指定登录接口及提交方式，可以指定任意路径
        this.setRequiresAuthenticationRequestMatcher(
                new AntPathRequestMatcher("/admin/system/index/login"
                        , "POST"));
        this.redisTemplate = redisTemplate;
        this.loginLogService = loginLogService;
    }

    /**
     * 登录认证
     *
     * @param req
     * @param resp
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse resp) throws AuthenticationException {
        try {
            LoginVo loginVo = new ObjectMapper().readValue(req.getInputStream(), LoginVo.class);

            Authentication authenticationToken = new UsernamePasswordAuthenticationToken(loginVo.getUsername(), loginVo.getPassword());
            return this.getAuthenticationManager().authenticate(authenticationToken);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 登录成功
     *
     * @param req
     * @param resp
     * @param chain
     * @param auth
     * @throws IOException
     * @throws +ServletException
     */
    @Override
    protected void successfulAuthentication(HttpServletRequest req,
                                            HttpServletResponse resp,
                                            FilterChain chain,
                                            Authentication auth) throws IOException, ServletException {

        CustomUser customUser = (CustomUser) auth.getPrincipal();
        // token
        String token = JwtHelper.createToken(customUser.getSysUser().getId(), customUser.getUsername());
        //   数据保存到Redis数据库
        redisTemplate.opsForValue().set(customUser.getUsername(), JSON.toJSONString(customUser.getAuthorities()));
        // 新增登录日志
        loginLogService.recordLoginLog(customUser.getUsername(), 0, IpUtil.getIpAddress(req), "登录成功");

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        ResponseUtil.out(resp, Result.ok(map));
    }


    /**
     * 登录失败
     *
     * @param req
     * @param resp
     * @param e
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest req, HttpServletResponse resp, AuthenticationException e) throws IOException, ServletException {
        //   instanceof: 判断它左边的对象是否是它右边的类 或该子类 的实例
        if (e.getCause() instanceof RuntimeException) {
            ResponseUtil.out(resp, Result.build(null, 204, e.getMessage()));

        } else {
            ResponseUtil.out(resp, Result.build(null, ResultCodeEnum.LOGIN_MOBLE_ERROR));
        }
    }
}
